const multer = require('multer');
const path = require('path');

// 配置 Multer
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'public/uploads/'); // 存储路径
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
        cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
    }
});

const upload = multer({ storage: storage });

// 上传单个文件的处理函数
const uploadFile = (req, res) => {
    upload.single('image')(req, res, (err) => {
        if (err) {
            return res.status(500).json({ message: '文件上传失败', error: err });
        }
        // 文件信息在 req.file 中
        const imageUrl = '/uploads/' + req.file.filename; // 返回文件访问路径
        res.status(200).json({ message: '文件上传成功', imageUrl: imageUrl });
    });
};

module.exports = { uploadFile };
